
#include "CSharpMutex.h"

#if Windows
// Remove some defines so it is not collided with the std libraries.
#	include <UndefCSharpKeywords.h>
#	include <mutex>
#elif Android
#	include <pthread.h>
#endif

std::map2<void*, Mutex*> s_instanceLocked;

Mutex::Mutex(void* instance)
	: _count(1)
	, _instance(instance)
{
	s_instanceLocked[instance] = this;

#if Windows
	m_mutex = new std::recursive_mutex();
#endif
}
Mutex::~Mutex()
{
	s_instanceLocked.erase(_instance);
	
#if Windows
	delete m_mutex;
	m_mutex = 0; // null
#endif
}
void Mutex::Lock()
{
#if Windows
	((std::recursive_mutex*)m_mutex)->lock();
#elif Android
	pthread_mutexattr_init(&Attr);
	pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE);
	pthread_mutex_init(&Mutex, &Attr);
	
	int rc = pthread_mutex_lock(&Mutex);
#endif
}
void Mutex::Unlock()
{
#if Windows
	((std::recursive_mutex*)m_mutex)->unlock();
#elif Android
	int rc = pthread_mutex_unlock(&Mutex);
#endif
}